package br.com.future.study.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

public class ConnectionPool {

    private static final String DB_HOST = "localhost";
    private static final String DB_USERNAME ="root";
    private static final String DB_PASSWD ="toor";
    private static final String DB_URL="jdbc:mysql://"+DB_HOST+":3306/future";
    private PoolingDataSource dataSource =  null;

	// Private constructor prevents instantiation from other classes
	@SuppressWarnings("unused")
	private ConnectionPool() {
		ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(DB_URL, DB_USERNAME, DB_PASSWD);
		ObjectPool connectionPool = new GenericObjectPool(null);
		PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
		dataSource = new PoolingDataSource(connectionPool);
	}

	/**
	 * SingletonHolder is loaded on the first execution of Singleton.getInstance() or 
	 * the first access to SingletonHolder.INSTANCE, not before.
	 */
	private static class SingletonHolder {
		public static final ConnectionPool INSTANCE = new ConnectionPool();
	}
//
//	public static ConnectionPoolSingleton getInstance() {
//		return SingletonHolder.INSTANCE;
//	}

	public static Connection getConnection() throws SQLException {
		return SingletonHolder.INSTANCE.dataSource.getConnection();
	}
}

